package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.ActionType;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 上传视频
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }




    /**
     * 关注/取消关注
     *
     * @param videoUserId 视频作者id
     * @param actionType  动作类型
     */
    public void followOrNot(Long videoUserId, ActionType actionType) {
        //1、调用API查询用户是否已经关注
        boolean followed = videoApi.hasFollowed(UserHolder.getUserId(), videoUserId);
        //2、根据动作类型actionType以及是否已关注来决定是否抛出异常
        if (followed && actionType.getType() == ActionType.LIKE.getType()) {
            //2.1、已关注+关注动作，抛出“用户已关注”异常
            throw new BusinessException(ErrorResult.focusError());
        } else if (!followed && actionType.getType() == ActionType.DISLIKE.getType()) {
            //2.2、未关注+取消关注动作，抛出“用户未关注”异常
            throw new BusinessException(ErrorResult.unFocusError());
        }
        //3、拼接redis的key，将用户的关注状态在redis中进行更新
        String key = Constants.VIDEO_INTERACT_KEY + videoUserId;
        String hashKey = Constants.VIDEO_FOCUS_HASHKEY + UserHolder.getUserId();
        //4、构造FocusUser对象
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setFollowUserId(videoUserId);
        if (actionType.getType() == ActionType.LIKE.getType()) {
            //5、关注
            //5.1、添加关注时间
            focusUser.setCreated(System.currentTimeMillis());
            //5.2、将用户的关注状态存入redis
            redisTemplate.opsForHash().put(key, hashKey, "1");
        } else {
            //6、取消关注,删除redis中的关注状态
            redisTemplate.opsForHash().delete(key, hashKey, "1");
        }
        //7、调用API更新数据到Mongodb
        videoApi.followOrNot(focusUser, actionType);
    }

    /**
     * 点赞视频/取消点赞视频
     *
     * @param videoId    视频id
     * @param actionType 动作类型
     */
    public void likeOrDislike(ObjectId videoId, ActionType actionType) {
        //1、拼接redis的key，查询用户是否已点赞
        String key = Constants.VIDEO_INTERACT_KEY + videoId.toHexString();
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        boolean liked = redisTemplate.opsForHash().hasKey(key, hashKey);
        //2、根据动作类型actionType以及是否已点赞来决定是否抛出异常
        if (liked && actionType.getType() == ActionType.LIKE.getType()) {
            //2.1、已点赞+点赞动作，抛出“用户已点赞”异常
            throw new BusinessException(ErrorResult.likeError());
        } else if (!liked && actionType.getType() == ActionType.DISLIKE.getType()) {
            //2.2、未点赞+取消点赞动作，抛出“用户未点赞”异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        if (actionType.getType() == ActionType.LIKE.getType()) {
            //3、点赞,将用户的点赞状态存入redis
            redisTemplate.opsForHash().put(key, hashKey, "1");
            mqMessageService.sendLogMessage(UserHolder.getUserId(), "0302", "video", videoId.toHexString());
        } else {
            //4、取消点赞,删除redis中的点赞状态
            redisTemplate.opsForHash().delete(key, hashKey);
            mqMessageService.sendLogMessage(UserHolder.getUserId(), "0303", "video", videoId.toHexString());
        }
        //5、调用API更新点赞数量
        videoApi.likeOrDislike(videoId, actionType);
    }

    /**
     * 查询视频评论列表
     */
    public PageResult queryComments(ObjectId videoId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = videoApi.queryComments(videoId, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                //判断hashKey是否存在
                String key = Constants.VIDEO_INTERACT_KEY + comment.getId().toHexString();
                String hashKey = Constants.COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        Video video = videoApi.findById(videoId);
        Integer commentCount = video.getCommentCount();
        //5、构造返回值
        return new PageResult(page, pagesize, Long.valueOf(commentCount), vos);
    }

    /**
     * 发布评论
     */
    public void comments(ObjectId videoId, String commentTxt) {
        //1、获取视频作者id
        Video video = videoApi.findById(videoId);
        Long publishUserId = video.getUserId();
        //2、构造Comment
        Comment comment = new Comment();
        comment.setPublishId(videoId);
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(commentTxt);
        comment.setUserId(UserHolder.getUserId());
        comment.setPublishUserId(publishUserId);
        comment.setCreated(System.currentTimeMillis());
        //3、调用API保存
        videoApi.saveVideoComment(comment);
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0304", "video", videoId.toHexString());
    }

    /**
     * 点赞评论/取消点赞评论
     */
    public void likeOrDislikeComment(ObjectId commentId, ActionType actionType) {
        //1、拼接redis的key，查询用户是否已点赞
        String key = Constants.VIDEO_INTERACT_KEY + commentId.toHexString();
        String hashKey = Constants.COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
        boolean liked = redisTemplate.opsForHash().hasKey(key, hashKey);
        //2、根据动作类型actionType以及是否已点赞来决定是否抛出异常
        if (liked && actionType.getType() == ActionType.LIKE.getType()) {
            //2.1、已点赞+点赞动作，抛出“用户已点赞”异常
            throw new BusinessException(ErrorResult.likeError());
        } else if (!liked && actionType.getType() == ActionType.DISLIKE.getType()) {
            //2.2、未点赞+取消点赞动作，抛出“用户未点赞”异常
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API更新评论点赞数
        videoApi.likeOrDislikeComment(commentId, actionType);
        if (actionType.getType() == ActionType.LIKE.getType()) {
            //4、点赞,将用户的点赞状态存入redis
            redisTemplate.opsForHash().put(key, hashKey, "1");
        } else {
            //5、取消点赞,删除redis中的点赞状态
            redisTemplate.opsForHash().delete(key, hashKey);
        }
    }
}





